package com.gxkj.drm.controllers;

import com.gxkj.drm.constant.WebConstant;
import com.gxkj.drm.dto.CodeMsg;
import com.gxkj.drm.entitys.PushUser;
import com.gxkj.drm.service.UserService;
import com.gxkj.drm.util.LoginHelper;
import com.gxkj.drm.util.MD5;
import com.gxkj.drm.util.ValidateCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by changxiangyang on 2017/10/9.
 */
@Controller
public class LoginController {

    private static final String LOGIN_STATUS = "status";
    private static final String LOGIN_MSG_FAIL = "用户名或密码错误,请重试";
    private static final String LOGIN_MSG_PARAM_ERROR = "请输入完整用户名和密码";
    private static final String LOGIN_MSG_LOGIN_ERROR = "登陆异常,请联系管理员";
    private static final String LOGIN_IMAGE_CODE_KEY = "imagecode";

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserService userService;

    /**
     * 注册页面
     * @return
     */
//    @Permission(needLogin = false, role = RoleType.USER)
    @RequestMapping(value = WebConstant.PATH_REGISTER_USER)
    public String register() {
        return WebConstant.PAGE_REGISTER_USER;
    }

    /**
     * 登出
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = WebConstant.PATH_LOGOUT)
    public String logout(final HttpServletRequest request, final HttpServletResponse response) {
        LoginHelper.logout(request, response);
        return "redirect:/login";
    }

    /**
     * 登录
     * @param user
     * @param model
     * @param request
     * @param response
     * @return
     */
//    @Permission(needLogin = false, role = RoleType.USER)
    @RequestMapping(value = "/user/doLogin", method = RequestMethod.POST)
    public String login(PushUser user, RedirectAttributes model, final HttpServletRequest request, final HttpServletResponse response) {
        try {
            if (StringUtils.isNotBlank(user.getName()) && StringUtils.isNotBlank(user.getPwd())) {
                PushUser u = this.userService.getUserByName(user.getName());
                if (u != null && MD5.md5(user.getPwd()).equals(u.getPwd())) {

                    LoginHelper.login(user, request, response);
                    return "redirect:" + WebConstant.PATH_HOME;
                } else {
                    model.addFlashAttribute(LOGIN_STATUS, new CodeMsg(CodeMsg.ERROR_CODE, LOGIN_MSG_FAIL));
                    return "redirect:/login" ;
                }
            } else {
                model.addFlashAttribute(LOGIN_STATUS, new CodeMsg(CodeMsg.ERROR_CODE, LOGIN_MSG_PARAM_ERROR));
                return "redirect:/login" ;
            }
        } catch (Exception e) {
            LOGGER.error("user login error:", e);
            model.addFlashAttribute(LOGIN_STATUS, new CodeMsg(CodeMsg.ERROR_CODE, LOGIN_MSG_LOGIN_ERROR));
            return "redirect:/login" ;
        }
    }


    /**
     * 登录页面
     * @param status 获取上一次"doLogin"操作的结果
     * @param model
     * @return
     */
    //@Permission(needLogin = false, role = RoleType.USER)
    @RequestMapping(value = {"/", "/login"})
    public String welcome(@ModelAttribute(LOGIN_STATUS)CodeMsg status, Model model){
        if (status != null) {
            // "doLogin"操作重定向到登陆页: 返回上次登陆的状态
            model.addAttribute("status", status);
        }
        return "login";
    }

    //登录获取验证码
//    @Permission(needLogin = false)
    @RequestMapping(value = WebConstant.PATH_LOGIN_IMAGE_CODE)
    @ResponseBody
    public String getSysManageLoginCode(HttpServletResponse response,
                                        HttpServletRequest request) {
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");//设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        ValidateCode randomValidateCode = new ValidateCode();
        try {
            randomValidateCode.getRandcode(request, response, LOGIN_IMAGE_CODE_KEY);// 输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //验证码验证
//    @Permission(needLogin = false, role = RoleType.USER)
    @RequestMapping(value = WebConstant.PATH_CHECK_IMAGE_CODE)
    @ResponseBody
    public CodeMsg checkCode(final HttpServletRequest request) {
        String validateCode = request.getParameter("validateCode");
        boolean isOK = ValidateCode.checkRandcode(request, LOGIN_IMAGE_CODE_KEY, validateCode);
        return isOK ? CodeMsg.SUCCESS : CodeMsg.ERROR;
    }
}
